﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebHoiChoMuaBan.Controllers.Helpers;
using WebHoiChoMuaBan.Models;
using WebHoiChoMuaBan.Controllers.Utility;
using System.Drawing;
using System.IO;

namespace WebHoiChoMuaBan.Controllers.Private
{
    public class PhotoController : PrivateController
    {
        private void Init()
        {
            ViewData["mid"] = "photo";
            LoadTimeAndCurrency();
        }

        public ActionResult List(int? uid, int? albumId)
        {
            if (uid == null)
                return HomePage();
            if (LoadMember(uid.Value) == null) //Load được Member
            {
                Init();
                ViewData["MemId"] = uid;
                PhotoAlbumHelper albumHelper = new PhotoAlbumHelper();
                List<PhotoAlbum> listAlbums = albumHelper.LoadAllAlbumsByUserId(uid.Value);
                ViewData["ListAlbums"] = listAlbums;
                ViewData["NumAlbums"] = listAlbums.Count;
                ViewData["ListPhotoOfAlbum"] = null;
                ViewData["NumPhoto"] = 0;

                if (listAlbums.Count != 0 && listAlbums != null)
                {
                    PhotoAlbum album = listAlbums[0];
                    PhotoHelper photoHelper = new PhotoHelper();
                    if (albumId == null)
                        albumId = album.AlbumId;
                    List<Photo> listPhotos = photoHelper.LoadAllPhotosOfAlbum((int)albumId);
                    ViewData["albumID"] = albumId;
                    ViewData["ListPhotoOfAlbum"] = listPhotos;
                    ViewData["NumPhoto"] = listPhotos.Count;
                }
                return View("~/Views/Private/PhotoList.aspx");
            }
            return HomePage();
        }

        public ActionResult Detail(int? uid,int? albumId, int photoId)
        {
            if (LoadMember(uid.Value) == null) //Load được Member
            {
                Init();
                PhotoHelper photoHelper = new PhotoHelper();
                Photo photo = photoHelper.GetPhotoById(photoId);

                //Load list photo of this album to show on the right panel
                ViewData["MemId"] = uid;
                ViewData["ListPhotoOfAlbum"] = null;
                ViewData["NumPhoto"] = 0;
                List<Photo> listPhotos = photoHelper.LoadAllPhotosOfAlbum((int)albumId);
                ViewData["albumID"] = albumId;
                ViewData["ListPhotoOfAlbum"] = listPhotos;
                //End load list photo of this album

                //Load two lastest albums
                PhotoAlbumHelper albumHelper = new PhotoAlbumHelper();
                List<PhotoAlbum> listAlbums = albumHelper.LoadAllAlbumsByUserId(uid.Value);
                ViewData["ListAlbums"] = listAlbums;
                //End load two lastest albums
                return View("~/Views/Private/PhotoDetail.aspx",photo);
            }
            return HomePage();
        }

        [HttpGet]
        public ActionResult Upload()
        {
            int uid;
            if (!this.IsLogin && Session["MemId"] == null)
                return HomePage();
            uid = (int)Session["MemId"];
            Init();
            //Load list of albums
            PhotoAlbumHelper albumHelper = new PhotoAlbumHelper();
            ViewData["ListAlbums"] = new SelectList(albumHelper.LoadAllAlbumsByUserId(uid), "AlbumId", "AlbumName");
            //End load list albums
            var result = LoadMember(uid);
            if (result == null) //Load được Member
                return View("~/Views/Private/PhotoUpload.aspx");
            return result;
        }

        [HttpPost]
        public ActionResult AddAlbum(int? uid, FormCollection f, HttpPostedFileBase AlbumThumbnail)
        {
            if (!this.IsLogin || uid == null)
                return HomePage();
            Init();
            var result = LoadMember(uid.Value);
            if (result == null) //Load được Member
            {
                PhotoAlbum album = new PhotoAlbum();
                album.AlbumName = f.Get("AblumName");
                album.MemId = (int)Session["MemId"];
                album.AlbumPostDate = DateTime.Now;
                //Add Thumbnail for album
                if (AlbumThumbnail != null)
                {
                    ImageHelper imgHelper = new ImageHelper();
                    if (imgHelper.CheckInfoIcon(AlbumThumbnail))
                    {
                        string imgName = "thumbnail_" + AlbumThumbnail.FileName;
                        album.AlbumThumb = imgName;
                        string path = Path.Combine(Server.MapPath("~/Content/Images/Upload/Thumbnail"), imgName);
                        imgHelper.uploadImage(path, AlbumThumbnail, 200, 100);
                    }
                }
                
                
                //Insert ablum into DB
                PhotoAlbumHelper ablumHelper = new PhotoAlbumHelper();
                ablumHelper.Add(album);
                ablumHelper.Save();
                return RedirectToAction("Upload", "Photo", new { uid = uid.Value});
            }
            return result;
        }

        [HttpPost]
        public ActionResult Index(IEnumerable<HttpPostedFileBase> files)
        {
            foreach (var file in files)
            {
                if (file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                    file.SaveAs(path);
                }
            }

            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult UploadPhoto2Album(int? uid, FormCollection f)
        {
            //Check permission of user
            if (!this.IsLogin || uid == null)
                return HomePage();
            Init();
            var result = LoadMember(uid.Value);
            if (result == null) //Load được Member
            {
                PhotoAlbum album = new PhotoAlbum();
                album.AlbumId = int.Parse(f.Get("selectAlbums"));
                album.MemId = (int)Session["MemId"];
                //Add photos into album
                PhotoHelper photoHelper = new PhotoHelper();
                int i = 1;
                foreach (string file in Request.Files)
                {
                    ImageHelper imgHelper = new ImageHelper();
                    HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                    if (imgHelper.CheckInfoIcon(hpf))
                    {
                        string imgName = "thumbnail_" + hpf.FileName;
                        string path_thumb = Path.Combine(Server.MapPath("~/Content/Images/Upload/Thumbnail"), imgName);
                        string path_image = Path.Combine(Server.MapPath("~/Content/Images/Upload"), hpf.FileName);
                        imgHelper.uploadImage(path_thumb, hpf, 183, 150);
                        imgHelper.uploadImage(path_image,hpf, 600, 450);
                        //Thêm vào CSDL 
                        Photo photo = new Photo();
                        photo.AlbumId = album.AlbumId;
                        photo.PhotoFileName = hpf.FileName;
                        photo.PhotoTitle = f.Get("textfield" + i);
                        photo.PhotoPostDate = DateTime.Now;
                        photoHelper.Add(photo);
                    }
                    i++;
                }

                photoHelper.Save();
            }

            return RedirectToAction("List", "Photo", new { uid = uid.Value });
        }

        [HttpGet]
        public ActionResult DeletePhoto(int photoId)
        {
            int uid;
            if (!this.IsLogin || Session["MemId"] == null)
                return HomePage();
            uid = (int)Session["MemId"];
            if (LoadMember(uid) == null) //Load được Member
            {
                Init();
                ImageHelper imgHelper = new ImageHelper();
                //Xóa các photo thuộc album trên
                PhotoHelper photoHelper = new PhotoHelper();
                Photo photo = photoHelper.GetPhotoById(photoId);
                
                photoHelper.Delete(photo);
                imgHelper.DeleteImg(Path.Combine(Server.MapPath("~/Content/Images/Upload/Thumbnail"), "thumbnail_" + photo.PhotoFileName));
                imgHelper.DeleteImg(Path.Combine(Server.MapPath("~/Content/Images/Upload"), photo.PhotoFileName));
                photoHelper.Save();
                return RedirectToAction("List", "Photo", new { uid = uid });
            }
            return HomePage();
        }

        [HttpGet]
        public ActionResult DeleteAlbum(int albumId)
        {
            int uid;
            if (!this.IsLogin || Session["MemId"] == null)
                return HomePage();
            uid = (int)Session["MemId"];
            if (LoadMember(uid) == null) //Load được Member
            {
                Init();
                ImageHelper imgHelper = new ImageHelper();
                //Xóa các photo thuộc album trên
                PhotoHelper photoHelper = new PhotoHelper();
                List<Photo> listPhoto = photoHelper.LoadAllPhotosOfAlbum(albumId);
                foreach (Photo photo in listPhoto)
                {
                    photoHelper.Delete(photo);
                    imgHelper.DeleteImg(Path.Combine(Server.MapPath("~/Content/Images/Upload/Thumbnail"), "thumbnail_" + photo.PhotoFileName));
                    imgHelper.DeleteImg(Path.Combine(Server.MapPath("~/Content/Images/Upload"), photo.PhotoFileName));
                    photoHelper.Save();
                }

                //Xóa album
                PhotoAlbumHelper albumHelper = new PhotoAlbumHelper();
                PhotoAlbum album = albumHelper.GetAlbumById(albumId);
                imgHelper.DeleteImg(Path.Combine(Server.MapPath("~/Content/Images/Upload/Thumbnail"), "thumbnail_" + album.AlbumThumb));
                albumHelper.Delete(album);
                albumHelper.Save();
                return RedirectToAction("List", "Photo", new { uid = uid });
            }
            return HomePage();
        }

        ///////////////////////// Function (not Action) ///////////
        //private void UploadImageToServer(HttpPostedFileBase hpf)
        //{
        //    ImageHelper imgHelper = new ImageHelper();
        //    if (imgHelper.CheckInfoIcon(hpf))
        //    {
        //        string thumbImgName = "thumbnail_" + hpf.FileName;
        //        Bitmap thumbImg = imgHelper.ResizeImage(hpf.InputStream, 200, 100);
        //        Bitmap image = imgHelper.ResizeImage(hpf.InputStream, 600, 350);
        //        var path_thumbImg = Path.Combine(Server.MapPath("~/Content/Images/Upload/Thumbnail"), thumbImgName);
        //        var path = Path.Combine(Server.MapPath("~/Content/Images/Upload"), hpf.FileName);
        //        image.Save(path);
        //        thumbImg.Save(path_thumbImg);
        //        image.Dispose();
        //    }
        //}
    }
}
